package client.logic;

/*Copyright 2010 Dietmar Wieser, Margit Mutschlechner and Florian Häser. All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, are
 permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice, this list of
 conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice, this list
 of conditions and the following disclaimer in the documentation and/or other materials
 provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY Dietmar Wieser, Margit Mutschlechner and Florian Häser ``AS IS''
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
 Dietmar Wieser, Margit Mutschlechner and Florian Häser OR
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 The views and conclusions contained in the software and documentation are those of the
 authors and should not be interpreted as representing official policies, either expressed
 or implied, of Dietmar Wieser, Margit Mutschlechner and Florian Häser.
 */
import java.util.Vector;

import android.app.Activity;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import client.Controller;
import client.gui.GUIController;
import client.logic.clientmodel.ClientAuthorResponse;
import client.logic.clientmodel.SuggestedAuthor;

/**
 * The BlueToothConnector scanns the bluetooth range and gets the mac-address of
 * the device.
 * 
 * @author Margit Mutschlechner
 */
public class BlueToothConnector extends Service {
	/** the devices in the bluetooth range */
	private static Vector<BluetoothDevice> devicesFound = null;

    // This is the object that receives interactions from clients.  See
    // RemoteService for a more complete example.
//	private final IBinder mBinder = new LocalBinder();
	
	/**
	 * Called when the activity is starting
	 * 
	 * @param savedInstanceState
	 *            If the activity is being re-initialized after previously being
	 *            shut down then this Bundle contains the data it most recently
	 *            supplied in onSaveInstanceState(Bundle).
	 */
	public void onCreate() {
		discoverDevices();
	}
	

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
//    /**
//     * Class for clients to access.  Because we know this service always
//     * runs in the same process as its clients, we don't need to deal with
//     * IPC.
//     */
//    public class LocalBinder extends Binder {
//        BlueToothConnector getService() {
//            return BlueToothConnector.this;
//        }
//    }

	/** Discovers the devices in the bluetooth range */
	public void discoverDevices() {
		devicesFound = new Vector<BluetoothDevice>();
		IntentFilter filterFound = new IntentFilter(
				BluetoothDevice.ACTION_FOUND);
		IntentFilter filterFinished = new IntentFilter(
				BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(bcReceiver, filterFound);
		registerReceiver(bcReceiver, filterFinished);
		BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
		boolean started = false;
		if (btAdapter != null) {
			started = btAdapter.startDiscovery();
		}
		if (!started) {
			Controller.getInstance().discoveryFinished(false);
		}
	}

	/**
	 * Gets all adequate authors that are in the bluetooth area of the current
	 * user.
	 * 
	 * @return a list of near authors
	 * @param the
	 *            whole list of adequate authors
	 * */
	public static ClientAuthorResponse getNearClients(
			ClientAuthorResponse authors) {
		ClientAuthorResponse car = new ClientAuthorResponse();
		if (authors != null) {
			Vector<SuggestedAuthor> allAuthors = authors.getSugAuthors();
			if (allAuthors != null) {
				for (int i = 0; i < allAuthors.size(); i++) {
					SuggestedAuthor sa = (SuggestedAuthor) allAuthors
							.elementAt(i);
					for (int j = 0; j < devicesFound.size(); j++) {
						BluetoothDevice btDevice = devicesFound.elementAt(j);
						if (btDevice.getAddress().equalsIgnoreCase(
								sa.getMacAddress())) {
							car.addSuggestedAuthor(sa);
						}
					}
				}
			}
		}
		return car;
	}

	/**
	 * Gets the mac-address of the current device.
	 * 
	 * @return the mac-address
	 * */
	public static String getMacAddress() {
		BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
		if (btAdapter == null) {
			GUIController.getInstance().showToast("Sorry, bluetooth is\nnot available on your phone");
		} else if (!btAdapter.isEnabled()) {
			GUIController.getInstance().showToast("Sorry, bluetooth is\nnot enabled on your phone");
		} else {
			String mac = BluetoothAdapter.getDefaultAdapter().getAddress();
			return mac;
		}
		return null;
	}

	/**
	 * BroadcastReceiver that reacts when a new bluetooth device was found or if
	 * the discovery of new devices is finished.
	 */
	private final BroadcastReceiver bcReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				devicesFound.addElement(device);
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
					.equals(action)) {
				Controller.getInstance().discoveryFinished(true);
//				terminate();
			}
		}
	};

//	/**
//	 * Called to finish this activity.
//	 */
//	private void terminate() {
//		this.stop();
//	}

	/**
	 * Performs any final cleanup before an activity is destroyed. This can
	 * happen either because the activity is finishing (someone called finish()
	 * on it, or because the system is temporarily destroying this instance of
	 * the activity to save space.
	 */
	public void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(bcReceiver);
//		Controller.getInstance().discoveryFinished(true);
	}

}
